//
//  DateManager.m
//  BCW
//
//  Created by Mac on 16/3/31.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "DateManager.h"

static DateManager *dateMgr;



@implementation DateManager{
    NSTimer *_timer;
}


+ (instancetype)shareDateMgr{
    return [[self alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dateMgr = [super allocWithZone:zone];
    });
    
    return dateMgr;
}

- (BCWDate)computeTimeDifferenceCrtTimeStr:(NSString *)str1 nextStr:(NSString *)str2{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date1 = [formatter dateFromString:str1];
    NSDate *date2 = [formatter dateFromString:str2];
    
    NSTimeInterval time1 = [date1 timeIntervalSince1970] * 1;
    NSTimeInterval time2 = [date2 timeIntervalSince1970] * 1;
    
    NSInteger cha = time2 - time1;
    _bcwDate = (BCWDate){cha / 60, cha % 60};
    return  _bcwDate;
}

- (void)beginTime{
    [_timer invalidate];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];
}

- (void)changeTime:(id)sender{
    if (_bcwDate.s == 0) {
        
        if (_bcwDate.m == 0 ) {
            // 发送通知
//            NSLog(@"倒计时结束");
            [_timer invalidate]; //清除计时器
            [[NSNotificationCenter defaultCenter] postNotificationName:EndTimeNoti object:nil];// 发送通知
            return;
        }
        _bcwDate.s = 60;
        _bcwDate.m -= 1;
    }
    
    self.bcwDate = (BCWDate){_bcwDate.m,  --_bcwDate.s};

}

@end
